package com.wk.springboot.hwjs;

public class NodeUtil {


    public static void main(String[] args) {
        Node node = getLastIndexNode(5);
        System.out.println(node);
    }

    /**
     * 一个不知道大小的node，怎么取出倒数第二个节点
     * 单向列表
     *
     * 采用双指针方法
     */
    public static Node getLastIndexNode(int index){

        /**
         * 创建一个node存储列表
         */
        Node first = new Node(null,0);
        Node node = first;
        for(int i=0;i<10;i++){
            Node nextNode = new Node(null,i+1);
            node.setNext(nextNode);
            node = nextNode;
        }

        Node node1 = first;
        Node node2 = first;
        Node resultNode = null;
        int count = 0;
        while(node1!=null){
            count++;
            if(count>=index){
                resultNode = node2;
                node2 = node2.getNext();
            }
            node1 = node1.getNext();
        }

        return resultNode;
    }

    /**
     * node 类
     */
    static class Node{

        private Node next;
        private Integer element;

        public Node() {
        }

        public Node(Node next, Integer element) {
            this.next = next;
            this.element = element;
        }

        public Node getNext() {
            return next;
        }

        public void setNext(Node next) {
            this.next = next;
        }

        public Integer getElement() {
            return element;
        }

        public void setElement(Integer element) {
            this.element = element;
        }

        @Override
        public String toString() {
            return "Node{" +
                    "next=" + next +
                    ", element=" + element +
                    '}';
        }
    }

}
